package com.hotai.service.impl;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hotai.comment.dtos.CellValue;
import com.hotai.comment.dtos.PageResponseResult;
import com.hotai.comment.dtos.ResponseResult;
import com.hotai.comment.enums.AppHttpCodeEnum;
import com.hotai.comment.pojo.CoursewareEquipment;
import com.hotai.comment.pojo.Equipment;
import com.hotai.comment.pojo.Institution;
import com.hotai.comment.pojo.UserStudent;
import com.hotai.mapper.CorsewareEquipmentMapper;
import com.hotai.mapper.EquipmentMapper;
import com.hotai.mapper.InstitutionMapper;
import com.hotai.mapper.UserStudentMapper;
import com.hotai.service.EquipmentService;
import com.hotai.vo.equipment.*;
import com.hotai.vo.equipment.EquiomentsAddByid;
import com.hotai.vo.usestudent.UserStudentListPage;
import net.minidev.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Mapper;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class EquipmentSeriviceImpl extends ServiceImpl<EquipmentMapper, Equipment> implements EquipmentService {

    @Autowired
    private  EquipmentMapper equipmentMapper;
    @Autowired
    private InstitutionMapper institutionMapper;

    @Autowired
    private UserStudentMapper  userStudentMapper;

    @Autowired
    private CorsewareEquipmentMapper corsewareEquipmentMapper;
    @Override
    public ResponseResult EuipmentPage(EquipmentList query) {
        //参数为空
        if (query == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        query.checkParam();

        PageHelper.startPage(query.getPage(),20);
        ArrayList<EquipmentPage> detaile = equipmentMapper.EquipmetPage(query);
        for (EquipmentPage EquipmentPage : detaile) {
            if (EquipmentPage.getInid()==2){
                EquipmentPage.setIname("个人");
            }
        }
        PageInfo<EquipmentPage> pageInfo = new PageInfo<>(detaile);
        PageResponseResult responseResult = new PageResponseResult(query.getPage(), pageInfo.getSize(),(int) pageInfo.getTotal());
        responseResult.setData(pageInfo.getList());
        return responseResult;
    }


    @Override
    public ResponseResult Institutiondetail(EquipmentDetileList queryware) {
        if (queryware==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查参数
        queryware.checkParam();
//        queryware.setPage((queryware.getPage()-1)*queryware.getSize());
//        ArrayList<Equipmentdetails> equdetailegen = equipmentMapper.Equdetailegen(queryware);


        PageHelper.startPage(queryware.getPage(),queryware.getSize());
        ArrayList<Equipmentdetails> detaile = equipmentMapper.Equdetaile(queryware);
        PageInfo<Equipmentdetails> pageInfo = new PageInfo<>(detaile);
        PageResponseResult responseResult = new PageResponseResult(queryware.getPage(), pageInfo.getSize(),(int) pageInfo.getTotal());
        responseResult.setData(pageInfo.getList());
        return responseResult;
    }



    @Override
    public ResponseResult Euipmentsave(EquiomentsAdd equiomentsAdd){
        Equipment equipment1 = equipmentMapper.selectOne(Wrappers.<Equipment>lambdaQuery().eq(Equipment::getXid, equiomentsAdd.getXid()));
        if (equipment1!=null){
            return ResponseResult.errorResult(567,"此序列号设备已存在!");
        }
        Equipment equipment = new Equipment();
        equipment.setCreateDate(new Date());
        equipment.setDeid(1);
        equipment.setStatus(1);
        equipment.setImg("https://sheb.oss-cn-beijing.aliyuncs.com/kejian/1659326556667.jpg");
        equiomentsAdd.setName(suiji());

        //个人
        if (equiomentsAdd.getInid()==2){
            BeanUtils.copyProperties(equiomentsAdd,equipment);
            equipmentMapper.insert(equipment);
        }else if (equiomentsAdd.getInid()==1 ){//机构
            String iname = equiomentsAdd.getIname();
            Institution institution = institutionMapper.selectOne(Wrappers.<Institution>lambdaQuery().eq(Institution::getName,iname));
            equiomentsAdd.setSid(institution.getId());
            BeanUtils.copyProperties(equiomentsAdd,equipment);
            equipmentMapper.insert(equipment);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }



    private String suiji() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 8; i++) {
            result += random.nextInt(8);
        }

        return result;
    }




    @Override
    public ResponseResult EuipmentAddByid() {
        List<Institution> institutions = institutionMapper.selectList(Wrappers.<Institution>lambdaQuery().eq(Institution::getDeid, 1));
        ArrayList<EquiomentsAddByid> equiomentsAddByids = new ArrayList<>();
        for (Institution institution : institutions) {
            EquiomentsAddByid equiomentsAddByid = new EquiomentsAddByid();
            equiomentsAddByid.setIname(institution.getName());
            equiomentsAddByid.setId(institution.getId());
            equiomentsAddByids.add(equiomentsAddByid);
        }
        return ResponseResult.okResult(equiomentsAddByids);
    }

    @Override
    public ResponseResult EuipmentXian(Integer id) {
          equipmentMapper.Xianzhi(id);
        userStudentMapper.UpdateShe(id);
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult GuanEuipmentPage(EquipmentList query) {
        if (query==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //检查参数
        query.checkParam();
        query.setPage((query.getPage()-1)*query.getSize());
        ArrayList<GuanEquPage> detaile = equipmentMapper.GuanEquList(query);
        PageResponseResult responseResult = new PageResponseResult(query.getPage()+1,query.getSize(), detaile.size());
        responseResult.setData(detaile);
        return responseResult;
    }

    @Override
    public ResponseResult GuanEuipmentDetaile(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ArrayList<GuanDetaile> detaile = equipmentMapper.GuanEquListDetaile(id);

        return  ResponseResult.okResult(detaile);
    }

    @Override
    public ResponseResult Daochu(HttpServletRequest request, HttpServletResponse response) {
        JSONObject result=new JSONObject();
        try {
            //准备数据
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("设备");
            //课程
            HSSFRow row = sheet.createRow(0);
            int num = 0;
            //创建第一行第一个单元格
            HSSFCell cell = row.createCell(num++);
            cell.setCellValue("序列号");
            cell = row.createCell(num++);
            cell.setCellValue("设备编号");
            cell = row.createCell(num++);
            cell.setCellValue("型号");
            cell = row.createCell(num++);
            cell.setCellValue("所属机构");
//            cell = row.createCell(num++);
//            cell.setCellValue("操作");

            //下载文件
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
//            response.setHeader("content-disposition",
//                    "attachment;filename=" + java.net.URLEncoder.encode("设备.xls", "UTF-8")
//                            + ";filename*=utf-8''" + java.net.URLEncoder.encode("设备.xls", "UTF-8"));
//

            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("设备.xls", "UTF-8"));
            response.setHeader("Connection", "close");
            response.setHeader("Content-Type", "application/octet-stream");
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PQCG, AppHttpCodeEnum.PQCG.getErrorMessage());
    }

    @Override
    public ResponseResult improtStu(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        try {
            HSSFWorkbook workbook2 = new HSSFWorkbook(file.getInputStream());
            HSSFSheet sheet2 = workbook2.getSheet("设备");
            int lastRowNum2 = sheet2.getLastRowNum();
            EqImportAdd eqImports = new EqImportAdd();
            ArrayList<EqImport> eqImportAdds = new ArrayList<>();
            for (int i = 1; i <= lastRowNum2; i++) {
                EqImport emp2 = new EqImport();
                HSSFRow row = sheet2.getRow(i);
                int num=0;
                HSSFCell cell = row.getCell(num++);
                String name = CellValue.getCellValue(cell);
                String xid= CellValue.getCellValue(row.getCell(num++));
                String model = CellValue.getCellValue(row.getCell(num++));
                String iname = CellValue.getCellValue(row.getCell(num++));
                if (!iname.equals("个人")){
                    Institution institution = institutionMapper.selectOne(Wrappers.<Institution>lambdaQuery().eq(Institution::getName,iname));
                    if (institution==null){
                        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前机构不存在");
                    }
                }
            emp2.setName(name);
            emp2.setXid(xid);
            emp2.setModel(model);
            emp2.setIname(iname);
            emp2.setTime(new Date());
            eqImportAdds.add(emp2);
            }
            return  ResponseResult.okResult(eqImportAdds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
    }

    @Override
    public ResponseResult improtAdd(EqImportAdd eqImportAdd) {

        for (EqImport eqImport : eqImportAdd.getEqImports()) {
            Equipment equipment = new Equipment();
            if (eqImport.getIname().equals("个人")){
                equipment.setInid(2);
                equipment.setSid(null);
            }else {
                Institution institution = institutionMapper.selectOne(Wrappers.<Institution>lambdaQuery().eq(Institution::getName, eqImport.getIname()));
                equipment.setSid(institution.getId());
                equipment.setInid(1);
            }
            equipment.setName(eqImport.getName());
            equipment.setXid(eqImport.getXid());
            equipment.setModel(eqImport.getModel());
            equipment.setDeid(1);
            equipment.setStatus(1);
            equipment.setCreateDate(new Date());
            equipmentMapper.insert(equipment);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult EuipmentXianZhi(String ide) {
        String[] split = ide.split(",");
        for (String s : split) {
            equipmentMapper.Xianzhi(Integer.parseInt(s));
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult Euipmentrelieve(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
        }
        equipmentMapper.relieve(id);
        userStudentMapper.Eqrelieve(id);
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult Euipmenteqrelieve(String ide) {
        if (ide==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
        }
        String[] split = ide.split(",");
        for (String s : split) {
            equipmentMapper.relieve(Integer.parseInt(s));
            userStudentMapper.Eqrelieve(Integer.parseInt(s));
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }


    @Override
    public ResponseResult EuipmentUpdate(EquiomenUpdate equiomentsAdd) {
        Equipment equipment1 = equipmentMapper.selectOne(Wrappers.<Equipment>lambdaQuery().eq(Equipment::getXid, equiomentsAdd.getXid()));
        if (equipment1==null){
            return  ResponseResult.errorResult(556,"未能找到此设备");
        }
        equipment1.setCapacity(equiomentsAdd.getCapacity());
        equipment1.setCourse(equiomentsAdd.getCourse());
        equipment1.setVersions(equiomentsAdd.getVersions());
        equipmentMapper.updateById(equipment1);
        CoursewareEquipment coursewareEquipment = new CoursewareEquipment();
        ArrayList<Integer> cid = equiomentsAdd.getCid();
        for (Integer integer : cid) {
            CoursewareEquipment coursewareEquipment1 = corsewareEquipmentMapper.selectOne(Wrappers.<CoursewareEquipment>lambdaQuery().eq(CoursewareEquipment::getCid, integer).eq(CoursewareEquipment::getEid,equipment1.getId()));
            if (coursewareEquipment1==null){
                coursewareEquipment.setEid(equipment1.getId());
                coursewareEquipment.setCid(integer);
                coursewareEquipment.setCreateDate(new Date());
                corsewareEquipmentMapper.insert(coursewareEquipment);
            }
        }
        return  ResponseResult.errorResult(AppHttpCodeEnum.PQCG,AppHttpCodeEnum.PQCG.getErrorMessage());
    }

    @Override
    public ResponseResult EuipmentWare(EquipmentWare equiomentsAdd) {
        if (equiomentsAdd==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
        }
         equipmentMapper.selectOne(Wrappers.<Equipment>lambdaQuery().eq(Equipment::getXid,equiomentsAdd.getXid()));
        CoursewareEquipment coursewareEquipment = new CoursewareEquipment();
        ArrayList<Integer> cid = equiomentsAdd.getCid();
        for (Integer integer : cid) {
            coursewareEquipment.setEid(coursewareEquipment.getId());
            coursewareEquipment.setCid(integer);
            coursewareEquipment.setCreateDate(new Date());
            corsewareEquipmentMapper.insert(coursewareEquipment);

        }
        return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
    }


}
